package com.spsoft.workflow.common.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.spsoft.workflow.common.enums.AssigneeTypeEnums;
import com.spsoft.core.exception.BaseException;
import com.spsoft.workflow.model.dto.json.ChildNode;
import com.spsoft.workflow.model.dto.json.Properties;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;
import com.spsoft.workflow.utils.BpmnModelUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.spsoft.workflow.common.CommonConstants.START_USER_ID;
import static com.spsoft.workflow.utils.BpmnModelUtils.getChildNode;


@Component
@Slf4j
public class CounterSignListener implements ExecutionListener {
    private static final long serialVersionUID = 5887214651164071999L;
    @Resource
    private RepositoryService repositoryService;
//    @Resource
//    private WfProcessBusinessService processBusinessService;

    @Override
    public void notify(DelegateExecution execution) {
        log.info("CounterSignListener");
        String currentActivityId = execution.getCurrentActivityId();
        ChildNode childNode = BpmnModelUtils.getFlowJson(execution.getProcessDefinitionId());
        List<String> assigneeList = new ArrayList<>();
        String variable = currentActivityId + "assigneeList";
        List usersValue = (List) execution.getVariable(variable);
        if (usersValue == null) {
            ChildNode currentNode = getChildNode(childNode, currentActivityId);
            if (currentNode == null) {
                throw new BaseException("查找审批人失败,请联系管理员重试");
            }
            Properties props = currentNode.getProps();
            String assignedType = props.getAssignedType();
            Map<String, Object> nobody = props.getNobody();
            if (AssigneeTypeEnums.ASSIGN_USER.getTypeName().equals(assignedType)) {
//                List<WfUserInfo> assignedUser = props.getAssignedUser();
//                for (WfUserInfo userInfo : assignedUser) {
//                    assigneeList.add(userInfo.getUserId());
//                }
            } else if (AssigneeTypeEnums.SELF_SELECT.getTypeName().equals(assignedType)) {

            } else if (AssigneeTypeEnums.LEADER.getTypeName().equals(assignedType)) {

            }
            //按角色，部门，多级主管查找审批人员
            else if (AssigneeTypeEnums.ROLE.getTypeName().equals(assignedType)
                    || AssigneeTypeEnums.LEADER_TOP.getTypeName().equals(assignedType)
                    || AssigneeTypeEnums.DEPT.getTypeName().equals(assignedType)
            ) {
                Long startUserId = Convert.toLong(execution.getVariable(START_USER_ID));
//                List<SysUserDepartVo> sysUserDepartVos = processBusinessService.findApprovalUser(props,startUserId);
//                if (CollUtil.isNotEmpty(sysUserDepartVos)) {
//                    for (SysUserDepartVo assigneeUser : sysUserDepartVos) {
//                        assigneeList.add(Convert.toStr(assigneeUser.getUserId()));
//                    }
//                }
            } else if (AssigneeTypeEnums.SELF.getTypeName().equals(assignedType)) {
                String startUserId = Convert.toStr(execution.getVariable(START_USER_ID));
                assigneeList.add(startUserId);
            } else if (AssigneeTypeEnums.FORM_USER.getTypeName().equals(assignedType)) {
                String formUser = props.getFormUser();
                List<JSONObject> assigneeUsers = execution.getVariable(formUser, List.class);
                if (assigneeUsers != null) {
                    for (JSONObject assigneeUser : assigneeUsers) {
                        assigneeList.add(assigneeUser.getString("id"));
                    }
                }

            }

            if (CollUtil.isEmpty(assigneeList)) {
                String handler = MapUtil.getStr(nobody, "handler");
                if ("TO_PASS".equals(handler)) {
                    assigneeList.add("100000");
                    execution.setVariable(variable, assigneeList);
                } else if ("TO_REFUSE".equals(handler)) {
                    execution.setVariable("autoRefuse", Boolean.TRUE);
                    assigneeList.add("100000");
                    execution.setVariable(variable, assigneeList);
                } else if ("TO_USER".equals(handler)) {
                    Object assignedUserObj = nobody.get("assignedUser");
                    if (assignedUserObj != null) {
                        List<JSONObject> assignedUser = (List<JSONObject>) assignedUserObj;
                        if (!assignedUser.isEmpty()) {
                            for (JSONObject object : assignedUser) {
                                assigneeList.add(object.getString("userId"));
                            }
                            execution.setVariable(variable, assigneeList);
                        } else {
                            assigneeList.add("100000");
                            execution.setVariable(variable, assigneeList);
                        }

                    }

                } else {
                    throw new BaseException("找不到审批人,请检查配置!!!");
                }
            } else {
                execution.setVariable(variable, assigneeList);
            }
        } else {
        }
    }
}
